from app.utils.id_generator import IdGenerator
from config.node_config import NODE_TYPES

class NodeService:
    def __init__(self, neo4j_driver):
        self.driver = neo4j_driver

    def create_cultural_item(self, data):
        """创建文物节点"""
        with self.driver.session() as session:
            # 生成唯一ID
            unique_id = IdGenerator.generate_unique_id('CulturalItem')
            
            props = {
                'id': unique_id,
                'name': data.get('name', ''),
                'category': data.get('category', ''),
                'period': data.get('period', ''),
                'description': data.get('description', ''),
                'dimensions': data.get('dimensions', ''),
                'height': float(data.get('height', 0)),
                'diameter_or_width': float(data.get('diameter_or_width', 0)),
                'base_diameter': float(data.get('base_diameter', 0)),
                'bell_diameter': float(data.get('bell_diameter', 0)),
                'original_inventory_number': data.get('original_inventory_number', '')
            }

            query = """
                CREATE (n:CulturalItem $props)
                RETURN n
            """
            result = session.run(query, props=props)
            new_node = result.single()['n']
            
            return {
                'identity': new_node.element_id,
                'labels': list(new_node.labels),
                'properties': dict(new_node),
                'elementId': f"4:c58d7524-43bb-4d30-88fd-7d4e40e19dff:{new_node.element_id}"
            }

    def create_node(self, node_type, data):
        """创建通用节点"""
        with self.driver.session() as session:
            unique_id = IdGenerator.generate_unique_id(node_type)
            props = {k: v for k, v in data.items() if v}
            props['id'] = unique_id

            query = f"""
                CREATE (n:{node_type} $props)
                RETURN n
            """
            result = session.run(query, props=props)
            new_node = result.single()['n']
            
            return {
                'identity': new_node.element_id,
                'labels': list(new_node.labels),
                'properties': dict(new_node),
                'elementId': f"4:c58d7524-43bb-4d30-88fd-7d4e40e19dff:{new_node.element_id}"
            }

    def get_nodes(self, node_type):
        """获取指定类型的所有节点"""
        with self.driver.session() as session:
            query = NODE_TYPES[node_type]['query']
            result = session.run(query)
            nodes = []
            for record in result:
                node = record['n']
                nodes.append({
                    'identity': node.element_id,
                    'labels': list(node.labels),
                    'properties': dict(node)
                })
            return nodes

    def update_node(self, node_type, node_id, data):
        """更新节点"""
        with self.driver.session() as session:
            props = {k: v for k, v in data.items() if v}
            query = f"""
                MATCH (n:{node_type})
                WHERE elementId(n) = $node_id
                SET n += $props
                RETURN n
            """
            result = session.run(query, node_id=int(node_id), props=props)
            updated_node = result.single()['n']
            return {
                'identity': updated_node.element_id,
                'labels': list(updated_node.labels),
                'properties': dict(updated_node)
            }

    def delete_node(self, node_type, node_id):
        """删除节点"""
        with self.driver.session() as session:
            query = f"""
                MATCH (n:{node_type})
                WHERE elementId(n) = $node_id
                DETACH DELETE n
            """
            session.run(query, node_id=int(node_id))
            return True

    def search_cultural_items(self, keyword):
        """搜索文物"""
        with self.driver.session() as session:
            result = session.run("""
                MATCH (ci:CulturalItem)
                WHERE ci.name =~ $pattern OR ci.description =~ $pattern
                RETURN ci
            """, pattern=f".*{keyword}.*")

            items = []
            for record in result:
                cultural_item = record['ci']
                items.append({
                    'element_id': cultural_item.element_id,
                    'labels': list(cultural_item.labels),
                    'properties': dict(cultural_item)
                })
            return items